package com.emre.daoGenerator.beanExtractor;

import java.io.File;
import java.io.IOException;

import com.emre.daoGenerator.GlobalConstants;
import com.emre.daoGenerator.bean.BeanDefinition;
import com.emre.daoGenerator.utils.DataTypeMethodMapper;
import com.emre.daoGenerator.utils.JavaCodeWriter;
import com.emre.daoGenerator.utils.StringUtils;

public class BeanExtractorClassGenerator 
{
	private BeanDefinition beanDefinition;
	
	private String path;
	
	public BeanExtractorClassGenerator(BeanDefinition beanDefinition, String path)
	{
		this.beanDefinition = beanDefinition;
		this.path = path;
	}
	
	public File generate() throws IOException
	{
		JavaCodeWriter writer = new JavaCodeWriter(path + beanDefinition.getName() + "Extractor.java");
		
		String packageDeclaration = "package " + GlobalConstants.topLevelPackageName + "." +GlobalConstants.beanExtractorPackageName + ";";
		writer.write(packageDeclaration, 0);
		writer.writeEmptyLine();
		
		writer.write(GlobalConstants.beanExtractorClassImportStatements, 0);
		
		writer.write("import " + GlobalConstants.topLevelPackageName + "." + GlobalConstants.beanPackageName + "." + beanDefinition.getName() + ";", 0);
		writer.writeEmptyLine();

		String classDeclaration = "public class " + beanDefinition.getName() + "Extractor implements ResultSetExtractor";
		writer.write(classDeclaration, 0);
		writer.write("{", 0);
		
		String extractDataMethodDeclaration = "public Object extractData(ResultSet rs ) throws SQLException, DataAccessException";
		writer.write(extractDataMethodDeclaration, 1);
		writer.write("{", 1);
		
		String beanDeclaration = beanDefinition.getName() + " bean = new " + beanDefinition.getName() + "();";
		writer.write(beanDeclaration, 2);
		for(int i = 1; i <= beanDefinition.getFields().size(); i++)
		{
			String setFieldExpr = StringUtils.setterMethodName(beanDefinition.getFields().get(i-1).getName());
			setFieldExpr += "(rs.getObject(" + i +") == null ? null : rs.";
			setFieldExpr += DataTypeMethodMapper.mapDataTypeToGetMethodName(beanDefinition.getFields().get(i-1).getType()) + "(" + i +"));";
			writer.write(setFieldExpr, 2);
		}
		writer.write("return bean;", 2);
		
		writer.write("}", 1);
		
		writer.write("}", 0);
						
		writer.close();
		
		return writer.getFile();
	}
}
